﻿/*!
 *  @Description:一些小的方法，不好分类的，通通放在这里
 * @Author:ZB,YPL
 * @Date:2014-03-31 
 */

var other = {};
//注册Array数组的indexof
other.registArrayIndexof = function () {
    if (!Array.prototype.indexOf) {
        Array.prototype.indexOf = function (elt /*, from*/) {
            var len = this.length >>> 0;

            var from = Number(arguments[1]) || 0;
            from = (from < 0)
                ? Math.ceil(from)
                : Math.floor(from);
            if (from < 0)
                from += len;

            for (; from < len; from++) {
                if (from in this &&
                    this[from] === elt)
                    return from;
            }
            return -1;
        };
    }
};
other.registArrayIndexof();

//解决分页控件f5后失效问题
other.oldUrl = window.location.href;
if (other.oldUrl.indexOf("#pageIndex") != -1) {
    window.location.href = other.oldUrl.split("#")[0];
}

//计时启用,目前这个方法只用于分页控件的分页计时，并且，各个页面也有自己的setPageStartTime方法
other.setPageStartTime = function () {
    window.commonPageStartTime = new Date();
};
//统计计时，同上
other.setPageEndTime = function () {
    if ('undefined' != typeof timehelper) {
        $("#timeCount").html("查询耗时" + timehelper.TimeDiffirence(window.commonPageStartTime, new Date()).msDiff + "毫秒");
    }

};
//显示透明层
other.showLoaderMask = function () {
    $('body').append('<div id="loaderMask"></div>');
};
//去掉透明层
other.hideLoaderMask = function () {
    $("#loaderMask").remove();
};

//处理分页第一页和最后一页
other.firstAndLastPage = function () {
    var currentPageIndex = parseInt($('#currentPageIndex').val());
    $('#currentPageIndex').val(currentPageIndex);
    var isLastPage = $('#isLastPage').val();

    if (currentPageIndex === 1) {
        $("#prevPage").addClass("disabled");
    }
    if (isLastPage != '0') {
        $("#nextPage").addClass("disabled");
    }
};

//查询未读信息，用在了各个母板页
other.getUnreadMessageCount = function () {
    $.AjaxAgency("/center/get-message-not-read-count", null, function (unreadCountData) {
        if (unreadCountData.indexOf("#error:") == -1) {
            if (parseInt(unreadCountData) <= 0) {
                $("#MesInfo").html("消息").css("width", "34px");
                $("#iUnreadMessage").html("");
            } else {
                $("#MesInfo").html("消息" + "<span class='ml4'>" + unreadCountData + "</span>").css("width", "54px");
                $("#iUnreadMessage").html(unreadCountData);
            }

        } else {
            $("#MesInfo").html("消息").css("width", "34px");
            $("#iUnreadMessage").html("");
        }
    });
};

//按钮启用
other.buttonStart = function (selector, disClassName) {
    if (disClassName) {
        $(selector).removeAttr("disabled").removeClass(disClassName);
    } else {
        $(selector).removeAttr("disabled").removeClass("btn-gray").addClass("btn-red");
    }
    $(selector).each(function (i, e) {
        if ($(e).attr("temp-value")) {
            $(e).val($(e).attr("temp-value"));
        }
    });
    //if ($(selector).attr("temp-value")) {
    //    $(selector).val($(selector).attr("temp-value"));
    //}
};

//按钮禁用
other.buttonDisable = function (selector, disClassName) {
    if (disClassName) {
        $(selector).attr("disabled", "disabled").addClass(disClassName);
    } else {
        $(selector).attr("disabled", "disabled").removeClass("btn-red").addClass("btn-gray");
    }
    if ($(selector).attr("disabled-show-txt")) {
        $(selector).attr("temp-value", $(selector).val());
        $(selector).val($(selector).attr("disabled-show-txt"));
    } else {
        //$(selector).attr("temp-value", $(selector).val());
        $(selector).each(function (i, e) {
            $(e).val($(e).attr("temp-value", $(e).val()));
        });
        $(selector).val("处理中...");
    }
};

//通过ajaxBeginForm提交表单时显示加载提示
other.onBegin = function () {
    //此方法在分页控件中
    if ("undefined" != typeof ajaxpageronbegin) {
        ajaxpageronbegin();
    }
    other.showLoaderMask();
};
other.onSuccess = function () {
    other.hideLoaderMask();
};

//全选（checkbox：控制checkbox，checkboxes：被全选的checkbox，fun：触发后回调方法）
other.selectAll = function (checkbox, checkboxes, fun, isUnBind) {
    if (!isUnBind) {
        $(checkbox).unbind("click");
    }

    $(checkbox).bind("click", function () {
        var isChecked = this.checked;
        $(checkboxes).each(function () {
            this.checked = isChecked;
        });

        if (fun && typeof fun == "function") {
            fun();
        }
    });
};


//全选（checkbox：控制checkbox，checkboxes：被全选的checkbox，fun：触发后回调方法）
other.selectAllByDisabled = function (checkbox, checkboxes, fun, isUnBind) {
    if (!isUnBind) {
        $(checkbox).unbind("click");
    }

    $(checkbox).bind("click", function () {
        var isChecked = this.checked;
        $(checkboxes).each(function () {
            if (!this.disabled) {
                this.checked = isChecked;
            }
            else {
                this.checked = false;
            }
        });

        if (fun && typeof fun == "function") {
            fun();
        }
    });
};



//两个数大小比较（第一个大于第二个互换）
other.numberBigOrSmall = function (selector1, selector2) {
    var tempMethod = function () {
        var temf = $(selector1).val();
        var temt = $(selector2).val();
        if (temf != "" && temt != "") {
            if (Number(temf) > Number(temt)) {
                $(selector2).val(temf);
                $(selector1).val(temt);
            }
        }
    };

    $(selector1).blur(tempMethod);
    $(selector2).blur(tempMethod);
};

//房号规则
other.houseRegex = function (code) {
    switch (code) {
        case "1":
            return "字母、数字任意组合";
        case "2":
            return "字母、数字、字符任意组合";
        case "3":
            return "楼层（2位）+房间号(2位数字)";
        case "4":
            return "楼层（2位）+房间号(1位字母)";
        case "5":
            return "楼层（2位）+房间号(数字或字母)";
        default:
            return "缺少房号规则";
    }
};

/*---------字符串处理部分--------------*/

//删除左右两端的空格 
other.trim = function (str) {
    if (str!=null&&str!="") {
return str.replace(/(^\s*)|(\s*$)/g, "");
    }
    
};
//删除左边的空格  
other.ltrim = function (str) {
    return str.replace(/(^\s*)/g, "");
};
//删除右边的空格  
other.rtrim = function rtrim(str) {
    return str.replace(/(\s*$)/g, "");
};

//防止重复提交,ele表示当前元素所属容器
other.obsortRepeatSubmit = function (ele) {
    if ($("#" + ele).find(".wrong:visible").length == 0) {
        $("#" + ele).find(".absort-repeat-submit").attr("disabled", "disabled");
    }
}

//对输入文本框中特殊字符转换
other.htmlConvertStr = function (selector, action, dynamic) {
    if (!action) {
        action = "blur";
    }
    var fun = function (e) {
        var tempValue = e.target.value;
        tempValue = tempValue.replace(/</g, '＜').replace(/>/g, '＞');

        $(selector).val(tempValue);
    }

    if (dynamic) {
        $(selector).live(action, fun);
    }
    else {
        $(selector).bind(action, fun);
    }
};

other.serialize = function (obj) {
    switch (typeof obj) {
        case "object":
            var str = "{";
            for (var o in obj) {
                str += '"' + o + '":"' + obj[o] + '",';
            }
            if (str.substr(str.length - 1) == ",")
                str = str.substr(0, str.length - 1);
            return str + "}";
            break;
            //case "Array":
            //    var str = "[";
            //    for (var o in obj) {
            //        str += Serialize(obj[o]) + ",";
            //    }
            //    if (str.substr(str.length - 1) == ",")
            //        str = str.substr(0, str.length - 1);
            //    return str + "]";
            //    break;
        case "Boolean":
            return "\"" + obj.toString() + "\"";
            break;
        case "Date":
            return "\"" + obj.toString() + "\"";
            break;
        case "Function":
            break;
        case "Number":
            return "\"" + obj.toString() + "\"";
            break;
        case "String":
            return "\"" + obj.toString() + "\"";
            break;
    }
};
/*---------字符串处理部分end--------------*/

//检测信息是否被选中,isMultiple是否可以多选
other.checkCount = function (isMultiple, selector, message1, message2, func) {
    var objCheck = $(selector), tempFuncVal = true;
    if (objCheck.length == 0) {
        $.OKDialogAgency('<div class="tc">' + message1 + '</div>');
        return false;
    } else if (objCheck.length > 1) {
        if (!isMultiple) {
            $.OKDialogAgency('<div class="tc">' + message2 + '</div>');
            return false;
        }

    }
    if (func) {
        tempFuncVal = func();
    }
    if (!tempFuncVal) {
        return false;
    }
    return objCheck;
};

//点击空白处隐藏
other.showAndHide = function (selector, id, func, id2) {
    $(document).unbind("click");
    $(document).bind("click", function (e) {
        var divpanel = $("#" + id);
        var tempoint = divpanel.offset();
        if (e.pageX > (tempoint.left + divpanel.width()) || e.pageX < tempoint.left || e.pageY > (tempoint.top + divpanel.height()) || e.pageY < tempoint.top) {
            if (id2) {
                if (e.target != $(selector)[0] && e.target != $('#' + id2)) {
                    divpanel.hide();
                    if (func) {
                        func();
                    }
                    $(document).unbind("click");
                }
            } else {
                if (e.target != $(selector)[0]) {
                    divpanel.hide();
                    if (func) {
                        func();
                    }
                    $(document).unbind("click");
                    if ($(this).find("i").hasClass("icon-statusModify-on")) {
                        $(this).find("i").removeClass("icon-statusModify-on");
                    }
                    if ($(this).find("i").hasClass("on")) {
                        $(this).find("i").removeClass("on");
                    }
                }
            }

        }
    });
};


//根据输入参数获取下拉框排序值
other.getOptionSort = function (startVal, endVal, isContainZero) {
    if (!(typeof startVal == "number" && typeof endVal == "number")) {
        return false;
    }
    if (startVal > endVal) {
        var tempVal = startVal;
        startVal = endVal;
        endVal = tempVal;
    }
    var tempResult = "";
    if (isContainZero) {
        for (var i = startVal; i <= endVal; i++) {
            if (i == 0) {
                continue;
            }
            tempResult += '<option value="' + i + '">' + i + '</option>';
        }
    } else {
        for (var i = startVal; i <= endVal; i++) {
            tempResult += '<option value="' + i + '">' + i + '</option>';
        }
    }

    return tempResult;
};

//传入一个选择器获得该选择器下所有含有name属性的值，返回值为json
other.getSubmitData = function (selector, isParemeterCombine) {
    var tempElements = $(selector).find("[name]");
    if (tempElements.length <= 0) {
        return false;
    }
    var jsonData = {};
    if (isParemeterCombine) {
        tempElements.each(function () {
            if (jsonData[$(this).attr("name")] == undefined) {
                jsonData[$(this).attr("name")] = $(this).attr("value");
            } else {
                jsonData[$(this).attr("name")] = jsonData[$(this).attr("name")] + "," + $(this).attr("value");
            }
        });
        return jsonData;
    }
    tempElements.each(function () {
        if (this.tagName == "INPUT") {
            if ($(this).attr("type") == "checkbox") {
                if ($(this).attr('checked') != undefined) {
                    if (jsonData[$(this).attr("name")] == undefined) {
                        jsonData[$(this).attr("name")] = $(this).attr("value");
                    } else {
                        jsonData[$(this).attr("name")] = jsonData[$(this).attr("name")] + "," + $(this).attr("value");
                    }

                }
            } else if ($(this).attr("type") == "text" || $(this).attr("type") == "password") {
                jsonData[$(this).attr("name")] = $(this).attr("value");

            } else if ($(this).attr("type") == "radio") {
                if ($(this).attr("checked")) {
                    jsonData[$(this).attr("name")] = $(this).val();
                }

            } else if ($(this).attr("type") == "hidden") {
                jsonData[$(this).attr("name")] = $(this).attr("value");
            }


        } else if (this.tagName == "SELECT") {
            jsonData[$(this).attr("name")] = $(this).find("option:selected").val();
        } else {
            jsonData[$(this).attr("name")] = $(this).attr("value");
        }


    });

    return jsonData;
};

//验证必填select是否为空(selId是对应select的id,con是弹出的错误信息)
other.selIsOrNotNull = function (selId, con) {
    $("#" + selId).find("select[selnotnull=1]").each(function () {
        if ($(this).val() == null || $(this).val() == -1) {
            $.OKDialogAgency('<div class="tc">' + con + '</div>');
            return false;
        }
    });
}

//一般ajax请求时做等待显示
other.loadDataPicture = function (selector) {
    //获取系统变量  
    var windowWidth = document.documentElement.clientWidth;
    var windowHeight = document.documentElement.clientHeight;
    var popupHeight = $(selector).height();
    var popupWidth = $(selector).width();
    //居中设置     
    $(selector).css({
        "display": "block",
        "position": "fixed",
        "top": windowHeight / 2 - popupHeight / 2,
        "left": windowWidth / 2 - popupWidth / 2
    });

};

//一般ajax成功后做取消显示
other.hidLoadDataPicture = function (selector) {
    $(selector).css("display", "none");
};

//根据图片相对路径获取图片全路径
other.getFullPhotoPath = function (baseUrl, photoPath) {
    var fullPath = photoPath;
    if (baseUrl.match(/^(http:\/\/|https:\/\/)/) && !fullPath.match(/^(http:\/\/|https:\/\/)/)) {
        fullPath = baseUrl + photoPath;
    }

    return fullPath;
};

//截取图片全路径为相对路径
other.cutPhotoPath = function (baseUrl, fullPhotoPath) {
    var reg = new RegExp(baseUrl);
    var photoPath = fullPhotoPath;
    if (reg.test(photoPath)) {
        photoPath = photoPath.replace(reg, "");
    }

    return photoPath;
}

//转换电话号码为末四位*格式(改为隐藏中间4位)
other.convertPhone = function (index,phone) {
    //var reg = /.{1,4}$/;
    //return phone.replace(reg, "****");

    if (phone != null && phone != "") {
        if (phone.length <= 4) { phone = "****"; }
        else
        {
            if (index == 2)//座机
            {
                var length = 0;
                if (phone.length == 5 || phone.length == 6)
                {
                    length = 1;
                }
                else 
                {
                    length = 2;
                }
                var mobile = phone.substr(length, 4);
                phone = phone.replace(mobile, "****");
            }
            else//手机
            {
                //var mobile = phone.substr(index, 4);
                //phone = phone.replace(mobile, "****");
                var reg = /(\d{3})\d{4}(\d{4})/;
                phone = phone.replace(reg, "$1****$2");
            }
            //phone = phone.replace(phone.substr(index, 4), "****");
        }
    }
    return phone;
}
other.formatTel = function (phone) {
    var reg = /.{1,4}$/;
    return phone.replace(reg, "****");
};

//处理undefined或null(property:属性名)
other.undefinedOrNull = function (property) {
    if (typeof property == 'undefined' || property == null || property == 'NULL') {
        return '';
    } else {
        return property;
    }
}

//处理小数点后的两个零
other.sliceZeros = function (element) {
    if (element.indexOf('.00') > 0) {
        return element.replace(/\.00/g, '');
    }
}

//对jqury扩展
//文本域显示剩余字数(id:文本域的id)
; (function ($) {
    $.extend({
        inputStatistics: function (id, max) {
            var jq_rN = 0;
            if ($("#" + id).val()) {
                jq_rN = max - $("#" + id).val().length;
            } else {
                jq_rN = max;
            }
            $("#" + id).parent().find(".jq_remainderNumber").remove();
            $("#" + id).parent().append('<span class="jq_remainderNumber">可输入<em class="red">' + jq_rN + '</em>个字符</span>');
            $("#" + id).bind("keyup mousedown", function () {
                var temthis = $(this);
                temthis.parent().find(".jq_remainderNumber").remove();
                var n = temthis.val().length;
                if (n >= max) {
                    temthis.val(temthis.val().substring(0, max));
                }
                temthis.parent().append('<span class="jq_remainderNumber">可输入<em class="red">' + (max - temthis.val().length) + '</em>个字符</span>');
                $(this).blur(function () {
                    if (temthis.val().length >= max) {
                        temthis.val(temthis.val().substring(0, max));
                    }
                });
            });
        },
        inputStatistics2: function (select) {
            var jq_rN = 0; var selector;
            if (typeof select === 'string') {
                selector = $(select);
            }
            else {
                selector = select;
            }
            if (selector.val()) {
                jq_rN = 200 - selector.val().length;
            } else {
                jq_rN = 200;
            }
            selector.parent().find(".jq_remainderNumber").remove();
            selector.parent().append('<span class="jq_remainderNumber">可输入<em class="red">' + jq_rN + '</em>个字符</span>');
            selector.bind("keyup mousedown", function () {
                var temthis = $(this);
                temthis.parent().find(".jq_remainderNumber").remove();
                var n = temthis.val().length;
                if (n >= 200) {
                    temthis.val(temthis.val().substring(0, 200));
                }
                temthis.parent().append('<span class="jq_remainderNumber">可输入<em class="red">' + (200 - temthis.val().length) + '</em>个字符</span>');
                $(this).blur(function () {
                    if (temthis.val().length >= 200) {
                        temthis.val(temthis.val().substring(0, 200));
                    }
                });
            });
        },
        inputStatistics3: function (id, max) {
            var jq_rN = 0;
            if ($("#" + id).val()) {
                jq_rN = max - $("#" + id).val().length;
            } else {
                jq_rN = max;
            }
            $("#" + id).parent().find(".jq_remainderNumber").remove();
            $("#" + id).parent().append('<span class="jq_remainderNumber">显示在官网经纪人详情页的我的店铺介绍，可输入<em class="red">' + jq_rN + '</em>个字符</span>');
            $("#" + id).bind("keyup mousedown", function () {
                var temthis = $(this);
                temthis.parent().find(".jq_remainderNumber").remove();
                var n = temthis.val().length;
                if (n >= max) {
                    temthis.val(temthis.val().substring(0, max));
                }
                temthis.parent().append('<span class="jq_remainderNumber">显示在官网经纪人详情页的我的店铺介绍，可输入<em class="red">' + (max - temthis.val().length) + '</em>个字符</span>');
                $(this).blur(function () {
                    if (temthis.val().length >= max) {
                        temthis.val(temthis.val().substring(0, max));
                    }
                });
            });
        },
    });
})(jQuery);
//字符串的扩展验证guid
String.prototype.IsGuid = function () {
    var reg0 = /^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$|^[0-9a-f]{32}$/;
    var reg1 = /^[0-9a-f]{8}([0-9a-f]{4}){3}[0-9a-f]{12}$|^[0-9a-f]{32}$/;
    return reg0.test(this) || reg1.test(this);
}